// pages/index.tsx
import React, { useState,useEffect } from 'react';
import { View, Button,Image,Text,usePageEvent,getStorage,setStorage,getLaunchOptionsSync,getAI2AgentVariableAgentVariableList,hideMenuButton } from '@ray-js/ray';
import styles from './index.module.less';
import PieChart from '../../components/PieChart';
import RealFlower from '../../assets/images/tab/RealFlower.png'
import BraveFlower from '../../assets/images/tab/BraveFlower.png'
import CaringFlower from '../../assets/images/tab/CaringFlower.png'
import AwareFlower from '../../assets/images/tab/AwareFlower.png'
import ActionFlower from '../../assets/images/tab/ActionFlower.png'
import FlowerReminder from '../../components/FlowerReminder'
import {customColors,RealText,BraveText,CaringText,AwareText,ActionText} from './content.jsx'
import FlowerLetter from '@/components/FlowerLetter';

export default function IndexPage() {
    const [RealFlowerExist,setRealFlowerExist]=useState(true);
    const [BraveFlowerExist,setBraveFlowerExist]=useState(true);
    const [CaringFlowerExist,setCaringFlowerExist]=useState(true);
    const [AwareFlowerExist,setAwareFlowerExist]=useState(true);
    const [ActionFlowerExist,setActionFlowerExist]=useState(true);
    const [PrimaryName,setPrimaryName]=useState('');
    const [Realvalue,setRealvalue]=useState(0);
    const [Bravevalue,setBravevalue]=useState(0);
    const [Caringvalue,setCaringvalue]=useState(0);
    const [Awarevalue,setAwarevalue]=useState(0);
    const [Actionvalue,setActionvalue]=useState(0);

    //每个提示文案弹窗
    const [Text1Exist,setText1Exist]=useState(false);
    const [Text2Exist,setText2Exist]=useState(false);
    const [Text3Exist,setText3Exist]=useState(false);
    const [Text4Exist,setText4Exist]=useState(false);
    const [Text5Exist,setText5Exist]=useState(false);
    const CloseText1=()=>{
      setText1Exist(false);
    }
    const CloseText2=()=>{
      setText2Exist(false);
    }
    const CloseText3=()=>{
      setText3Exist(false);
    }
    const CloseText4=()=>{
      setText4Exist(false);
    }

    const CloseText5=()=>{
      setText5Exist(false);
    }

    //每封信弹窗文案
    const [LetterText1Exist,setLetterText1Exist]=useState(false);
    const [LetterText2Exist,setLetterText2Exist]=useState(false);
    const [LetterText3Exist,setLetterText3Exist]=useState(false);
    const [LetterText4Exist,setLetterText4Exist]=useState(false);
    const [LetterText5Exist,setLetterText5Exist]=useState(false);
    const CloseFlowerLetter1=()=>{
      setLetterText1Exist(false);
    }
    const CloseFlowerLetter2=()=>{
      setLetterText2Exist(false);
    }
    const CloseFlowerLetter3=()=>{
      setLetterText3Exist(false);
    }
    const CloseFlowerLetter4=()=>{
      setLetterText4Exist(false);
    }
    const CloseFlowerLetter5=()=>{
      setLetterText5Exist(false);
    }

    //每次弹窗提示
    useEffect(() => {
        const { query: { deviceId } } = getLaunchOptionsSync();
        getStorage({
          key: deviceId+'2',
          success(res) {
            const flowerTypes = [
              { 
                compareKey: 'RealvalueCompare', 
                valueKey: 'Realvalue', 
                existVar: RealFlowerExist, 
                setText: setText1Exist ,
                setLetter:setLetterText1Exist,
                LetterKey:'LetterText1Exist'
              },
              { 
                compareKey: 'BravevalueCompare', 
                valueKey: 'Bravevalue', 
                existVar: BraveFlowerExist, 
                setText: setText2Exist ,
                setLetter:setLetterText2Exist,
                LetterKey:'LetterText2Exist'
              },
              { 
                compareKey: 'CaringvalueCompare', 
                valueKey: 'Caringvalue', 
                existVar: CaringFlowerExist, 
                setText: setText3Exist ,
                setLetter:setLetterText3Exist,
                LetterKey:'LetterText3Exist'
              },
              { 
                compareKey: 'AwarevalueCompare', 
                valueKey: 'Awarevalue', 
                existVar: AwareFlowerExist, 
                setText: setText4Exist ,
                setLetter:setLetterText4Exist,
                LetterKey:'LetterText4Exist'
              },
              { 
                compareKey: 'ActionvalueCompare', 
                valueKey: 'Actionvalue', 
                existVar: ActionFlowerExist, 
                setText: setText5Exist ,
                setLetter:setLetterText5Exist,
                LetterKey:'LetterText5Exist'
              }
            ];
      
            // 初始化或获取比较值
            const compareValues = {};
            if (res.data === null) {
              const initData = {};
              flowerTypes.forEach(flower => {
                initData[flower.compareKey] = 0;
                compareValues[flower.compareKey] = 0;
              });
              setStorage({
                key: deviceId+'2',
                data: initData
              });
            } else {
              flowerTypes.forEach(flower => {
                compareValues[flower.compareKey] = Number(res.data[flower.compareKey]);
              });
            }
      
            getStorage({
              key: deviceId+'1',
              success(res) {
                flowerTypes.forEach(flower => {
                  const currentValue = Number(res.data[flower.valueKey]);
                  const compareValue = compareValues[flower.compareKey];
                  
                  if (compareValue !== currentValue && !flower.existVar) {
                    getStorage({
                      key: deviceId+'2',
                      success(res) {
                        setStorage({
                          key: deviceId+'2',
                          data: {
                            ...res.data,
                            [flower.compareKey]: currentValue
                          },
                          success() {
                            flower.setText(true);
                          }
                        });
                      }
                    });
                  }

                  if(currentValue===9 && !flower.existVar)
                    {
                      getStorage({
                        key:deviceId+'3',
                        success(res){
                          if(res.data===null){
                            setStorage({
                              key:deviceId+'3',
                              data:{
                                LetterText1Exist:false,
                                LetterText2Exist:false,
                                LetterText3Exist:false,
                                LetterText4Exist:false,
                                LetterText5Exist:false
                              },
                              success(){
                                getStorage({
                                  key:deviceId+'3',
                                  success(res){
                                    setStorage({
                                      key:deviceId+'3',
                                      data:{
                                        ...res.data,
                                        [flower.LetterKey]:true
                                      }
                                    })
                                  }
                                })
                                
                                flower.setLetter(true);
                              },
                              fail(res){
                                console.log('失败',res)
                              }
                            })
                          }
                          else if(res.data[flower.LetterKey]===false)
                          {
                            setStorage({
                              key:deviceId+'3',
                              data:{
                                ...res.data,
                                [flower.LetterKey]:true
                              }
                            })
                            flower.setLetter(true);
                          }
                        }
                      }) 
                    }
                });
              }
            });
          }
        });
      }, [RealFlowerExist, BraveFlowerExist, CaringFlowerExist, AwareFlowerExist, ActionFlowerExist]);

    useEffect(() => {       //每两秒取一次Value值
      const { query: { deviceId } } = getLaunchOptionsSync();
        const interval = setInterval(async() => {
            getStorage({
                key:deviceId+'1',
                success(res){
                    const result1=Number(res.data.Realvalue);
                    const result2=Number(res.data.Bravevalue);
                    const result3=Number(res.data.Caringvalue);
                    const result4=Number(res.data.Awarevalue);
                    const result5=Number(res.data.Actionvalue);
                    setRealvalue(result1);
                    setBravevalue(result2);
                    setCaringvalue(result3);
                    setAwarevalue(result4);
                    setActionvalue(result5);
                }
            })
            
        }, 2000); 
    
        return () => clearInterval(interval); // 组件卸载时清理定时器
      }, []);
       
      const [username,setusername]=useState('');
      useEffect(() => {
        const { query: { deviceId } } = getLaunchOptionsSync();
        //获取用户名
        const FetchVariable=async()=>{
          try{
            const newVariables = await getAI2AgentVariableAgentVariableList({  
              devId: deviceId,  
            });
            const call = newVariables.find(user => user.variableKey === 'custom.call')?.variableValue;
            setusername(call);
          } catch{
      
          }
        }
        FetchVariable();

        getStorage({
          key:deviceId+'1',
          success(res){
              const result1=Number(res.data.Realvalue);
              const result2=Number(res.data.Bravevalue);
              const result3=Number(res.data.Caringvalue);
              const result4=Number(res.data.Awarevalue);
              const result5=Number(res.data.Actionvalue);
              setRealvalue(result1);
              setBravevalue(result2);
              setCaringvalue(result3);
              setAwarevalue(result4);
              setActionvalue(result5);
          }
      })
        hideMenuButton({  });
        getStorage({
          key: 'FlowerExist',
          success(res) {
            const flowerTypes = [
              { key: 'RealFlower', name: '真实之花', setter: setRealFlowerExist },
              { key: 'BraveFlower', name: '勇敢之花', setter: setBraveFlowerExist },
              { key: 'CaringFlower', name: '关怀之花', setter: setCaringFlowerExist },
              { key: 'AwareFlower', name: '觉知之花', setter: setAwareFlowerExist },
              { key: 'ActionFlower', name: '行动之花', setter: setActionFlowerExist }
            ];
      
            for (const flower of flowerTypes) {
              const exists = Boolean(res.data[flower.key]);
              if (exists) {
                // 设置所有花朵的状态
                flowerTypes.forEach(ft => {
                  ft.setter(ft.key === flower.key ? !exists : exists);
                });
                
                setPrimaryName(flower.name);
                
                // 更新存储
                getStorage({
                  key: 'FlowerExist',
                  success(res) {
                    setStorage({
                      key: 'FlowerExist',
                      data: {
                        ...res.data,
                        [flower.key]: false
                      }
                    });
                  }
                });
                
                break; // 找到一个存在的花朵后就退出循环
              }
            }
          }
        });
      });

    const OpenRealFlower=()=>{
        setRealFlowerExist(false);
        setBraveFlowerExist(true);
        setCaringFlowerExist(true);
        setAwareFlowerExist(true);
        setActionFlowerExist(true);
        setPrimaryName('真实之花');
    }
    const OpenBraveFlower=()=>{
        setRealFlowerExist(true);
        setBraveFlowerExist(false);
        setCaringFlowerExist(true);
        setAwareFlowerExist(true);
        setActionFlowerExist(true);
        setPrimaryName('勇敢之花');
    }
    const OpenCaringFlower=()=>{
        setRealFlowerExist(true);
        setBraveFlowerExist(true);
        setCaringFlowerExist(false);
        setAwareFlowerExist(true);
        setActionFlowerExist(true);
        setPrimaryName('关怀之花');
    }
    const OpenAwareFlower=()=>{
        setRealFlowerExist(true);
        setBraveFlowerExist(true);
        setCaringFlowerExist(true);
        setAwareFlowerExist(false);
        setActionFlowerExist(true);
        setPrimaryName('觉知之花');
    }
    const OpenActionFlower=()=>{
        setRealFlowerExist(true);
        setBraveFlowerExist(true);
        setCaringFlowerExist(true);
        setAwareFlowerExist(true);
        setActionFlowerExist(false);
        setPrimaryName('行动之花');
    }

  return(
    <>
        {   Text1Exist && Realvalue!=0 &&
            <FlowerReminder text={RealText[Realvalue]} onClose={CloseText1}></FlowerReminder>}
        {   Text2Exist && Bravevalue!=0 &&
            <FlowerReminder text={BraveText[Bravevalue]} onClose={CloseText2}></FlowerReminder>}
        {   Text3Exist && Caringvalue!=0 &&
            <FlowerReminder text={CaringText[Caringvalue]} onClose={CloseText3}></FlowerReminder>}
        {   Text4Exist && Awarevalue!=0 &&
            <FlowerReminder text={AwareText[Awarevalue]} onClose={CloseText4}></FlowerReminder>}
        {   Text5Exist && Actionvalue!=0 &&
            <FlowerReminder text={ActionText[Actionvalue]} onClose={CloseText5}></FlowerReminder>}

        {   LetterText1Exist &&
            <FlowerLetter UserName={username} text={RealText[0]} onClose={CloseFlowerLetter1}></FlowerLetter>
        }
        {   LetterText2Exist &&
            <FlowerLetter UserName={username} text={BraveText[0]} onClose={CloseFlowerLetter2}></FlowerLetter>
        }
        {   LetterText3Exist &&
            <FlowerLetter UserName={username} text={CaringText[0]} onClose={CloseFlowerLetter3}></FlowerLetter>
        }
        {   LetterText4Exist &&
            <FlowerLetter UserName={username} text={AwareText[0]} onClose={CloseFlowerLetter4}></FlowerLetter>
        }
        {   LetterText5Exist &&
            <FlowerLetter UserName={username} text={ActionText[0]} onClose={CloseFlowerLetter5}></FlowerLetter>
        }


        <View className={styles.bg}>
          

        {   !RealFlowerExist &&
            <View className={styles.primarypiechart}>
            <PieChart
                color1={Realvalue>=1 ? customColors[1]:customColors[0]}
                color2={Realvalue>=2 ? customColors[2]:customColors[0]}
                color3={Realvalue>=3 ? customColors[3]:customColors[0]}
                color4={Realvalue>=4 ? customColors[4]:customColors[0]}
                color5={Realvalue>=5 ? customColors[5]:customColors[0]}
                color6={Realvalue>=6 ? customColors[6]:customColors[0]}
                color7={Realvalue>=7 ? customColors[7]:customColors[0]}
                color8={Realvalue>=8 ? customColors[8]:customColors[0]}
                color9={Realvalue>=9 ? customColors[9]:customColors[0]}
            >
            </PieChart>
        </View>}
        {   !BraveFlowerExist &&
            <View className={styles.primarypiechart}>
            <PieChart
                color1={Bravevalue>=1 ? customColors[1]:customColors[0]}
                color2={Bravevalue>=2 ? customColors[2]:customColors[0]}
                color3={Bravevalue>=3 ? customColors[3]:customColors[0]}
                color4={Bravevalue>=4 ? customColors[4]:customColors[0]}
                color5={Bravevalue>=5 ? customColors[5]:customColors[0]}
                color6={Bravevalue>=6 ? customColors[6]:customColors[0]}
                color7={Bravevalue>=7 ? customColors[7]:customColors[0]}
                color8={Bravevalue>=8 ? customColors[8]:customColors[0]}
                color9={Bravevalue>=9 ? customColors[9]:customColors[0]}
            >
            </PieChart>
        </View>}
        {   !CaringFlowerExist &&
            <View className={styles.primarypiechart}>
            <PieChart
                color1={Caringvalue>=1 ? customColors[1]:customColors[0]}
                color2={Caringvalue>=2 ? customColors[2]:customColors[0]}
                color3={Caringvalue>=3 ? customColors[3]:customColors[0]}
                color4={Caringvalue>=4 ? customColors[4]:customColors[0]}
                color5={Caringvalue>=5 ? customColors[5]:customColors[0]}
                color6={Caringvalue>=6 ? customColors[6]:customColors[0]}
                color7={Caringvalue>=7 ? customColors[7]:customColors[0]}
                color8={Caringvalue>=8 ? customColors[8]:customColors[0]}
                color9={Caringvalue>=9 ? customColors[9]:customColors[0]}
            >
            </PieChart>
        </View>}
        {   !AwareFlowerExist &&
            <View className={styles.primarypiechart}>
            <PieChart
                color1={Awarevalue>=1 ? customColors[1]:customColors[0]}
                color2={Awarevalue>=2 ? customColors[2]:customColors[0]}
                color3={Awarevalue>=3 ? customColors[3]:customColors[0]}
                color4={Awarevalue>=4 ? customColors[4]:customColors[0]}
                color5={Awarevalue>=5 ? customColors[5]:customColors[0]}
                color6={Awarevalue>=6 ? customColors[6]:customColors[0]}
                color7={Awarevalue>=7 ? customColors[7]:customColors[0]}
                color8={Awarevalue>=8 ? customColors[8]:customColors[0]}
                color9={Awarevalue>=9 ? customColors[9]:customColors[0]}
            >
            </PieChart>
        </View>}
        {   !ActionFlowerExist &&
            <View className={styles.primarypiechart}>
            <PieChart
                color1={Actionvalue>=1 ? customColors[1]:customColors[0]}
                color2={Actionvalue>=2 ? customColors[2]:customColors[0]}
                color3={Actionvalue>=3 ? customColors[3]:customColors[0]}
                color4={Actionvalue>=4 ? customColors[4]:customColors[0]}
                color5={Actionvalue>=5 ? customColors[5]:customColors[0]}
                color6={Actionvalue>=6 ? customColors[6]:customColors[0]}
                color7={Actionvalue>=7 ? customColors[7]:customColors[0]}
                color8={Actionvalue>=8 ? customColors[8]:customColors[0]}
                color9={Actionvalue>=9 ? customColors[9]:customColors[0]}
            >
            </PieChart>
        </View>}


        {   !RealFlowerExist &&
            <View className={styles.Primarybox} style={{backgroundColor:'#d4e2f8'}}>
            <Button className={styles.PrimaryFlowerBtn}>
                <Image className={styles.PrimaryFlowerImg} src={RealFlower}></Image>
            </Button>
            <Text className={styles.PrimaryFlowerName}>真实之花</Text>
            <Text className={styles.PrimaryFlowerContent}>真实之花开了{Realvalue}瓣啦,它说:我喜欢你带着恐惧依旧去做的样子</Text>
        </View>}
        {   !BraveFlowerExist &&
            <View className={styles.Primarybox} style={{backgroundColor:'#ebdae7'}}>
            <Button className={styles.PrimaryFlowerBtn}>
                <Image className={styles.PrimaryFlowerImg} src={BraveFlower}></Image>
            </Button>
            <Text className={styles.PrimaryFlowerName}>勇敢之花</Text>
            <Text className={styles.PrimaryFlowerContent}>勇敢之花开了{Bravevalue}瓣啦,它说:我喜欢你带着恐惧依旧去做的样子</Text>
        </View>}
        {   !CaringFlowerExist &&
            <View className={styles.Primarybox} style={{backgroundColor:'#d2e8ee'}}>
            <Button className={styles.PrimaryFlowerBtn}>
                <Image className={styles.PrimaryFlowerImg} src={CaringFlower}></Image>
            </Button>
            <Text className={styles.PrimaryFlowerName}>关怀之花</Text>
            <Text className={styles.PrimaryFlowerContent}>关怀之花开了{Caringvalue}瓣啦,它说:我喜欢你带着恐惧依旧去做的样子</Text>
        </View>}
        {   !AwareFlowerExist &&
            <View className={styles.Primarybox} style={{backgroundColor:'#dadef9'}}>
            <Button className={styles.PrimaryFlowerBtn}>
                <Image className={styles.PrimaryFlowerImg} src={AwareFlower}></Image>
            </Button>
            <Text className={styles.PrimaryFlowerName}>觉知之花</Text>
            <Text className={styles.PrimaryFlowerContent}>觉知之花开了{Awarevalue}瓣啦,它说:我喜欢你带着恐惧依旧去做的样子</Text>
        </View>}
        {   !ActionFlowerExist &&
            <View className={styles.Primarybox} style={{backgroundColor:'#ebe2dd'}}>
            <Button className={styles.PrimaryFlowerBtn}>
                <Image className={styles.PrimaryFlowerImg} src={ActionFlower}></Image>
            </Button>
            <Text className={styles.PrimaryFlowerName}>行动之花</Text>
            <Text className={styles.PrimaryFlowerContent}>行动之花开了{Actionvalue}瓣啦,它说:我喜欢你带着恐惧依旧去做的样子</Text>
        </View>}    

        <Text className={styles.OtherText}>其他花朵</Text>

        <Text className={styles.Name}>{PrimaryName}</Text>

        <View className={styles.FlowerContainer}>

            {   RealFlowerExist &&
                <View className={styles.box} onClick={OpenRealFlower} style={{backgroundColor:'#d4e2f8'}}>
                <Button className={styles.FlowerBtn}>
                    <Image className={styles.FlowerImg} src={RealFlower}></Image>
                </Button>
                <Text className={styles.FlowerName}>真实之花</Text>
                <Text className={styles.FlowerContent}>在你接纳真实自己时绽放</Text>
            </View>}

            {   BraveFlowerExist &&
                <View className={styles.box} onClick={OpenBraveFlower} style={{backgroundColor:'#ebdae7'}}>
                <Button className={styles.FlowerBtn}>
                    <Image className={styles.FlowerImg} src={BraveFlower}></Image>
                </Button>
                <Text className={styles.FlowerName}>勇敢之花</Text>
                <Text className={styles.FlowerContent}>在你面对恐惧,勇敢迈出第一步时绽放</Text>
            </View>}

            {   CaringFlowerExist &&
                <View className={styles.box} onClick={OpenCaringFlower} style={{backgroundColor:'#d2e8ee'}}>
                <Button className={styles.FlowerBtn}>
                    <Image className={styles.FlowerImg} src={CaringFlower}></Image>
                </Button>
                <Text className={styles.FlowerName}>关怀之花</Text>
                <Text className={styles.FlowerContent}>在你照顾好自己、关爱他人时绽放</Text>
            </View>}

            {   AwareFlowerExist &&
                <View className={styles.box} onClick={OpenAwareFlower} style={{backgroundColor:'#dadef9'}}>
                <Button className={styles.FlowerBtn}>
                    <Image className={styles.FlowerImg} src={AwareFlower}></Image>
                </Button>
                <Text className={styles.FlowerName}>觉知之花</Text>
                <Text className={styles.FlowerContent}>在你自我觉察时绽放</Text>
            </View>}

            {   ActionFlowerExist &&
                <View className={styles.box} onClick={OpenActionFlower} style={{backgroundColor:'#ebe2dd'}}>
                <Button className={styles.FlowerBtn}>
                    <Image className={styles.FlowerImg} src={ActionFlower}></Image>
                </Button>
                <Text className={styles.FlowerName}>行动之花</Text>
                <Text className={styles.FlowerContent}>在你完成积极行动时绽放</Text>
            </View>}

        </View>
        </View>
    </>
  );
}